<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>车载物流AI助手</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link
      href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css"
      rel="stylesheet"
    />
    <script>
      tailwind.config = {
        theme: {
          extend: {
            colors: {
              primary: "#3b82f6",
              secondary: "#10b981",
              dark: "#1e293b",
              light: "#f8fafc",
            },
            fontFamily: {
              sans: ["Inter", "system-ui", "sans-serif"],
            },
          },
        },
      };
    </script>
    <style type="text/tailwindcss">
      @layer utilities {
        .content-auto {
          content-visibility: auto;
        }
        .scrollbar-hide {
          -ms-overflow-style: none;
          scrollbar-width: none;
        }
        .scrollbar-hide::-webkit-scrollbar {
          display: none;
        }
        .message-bubble-user {
          border-radius: 18px 18px 4px 18px;
        }
        .message-bubble-ai {
          border-radius: 18px 18px 18px 4px;
        }
        .typing-indicator {
          display: inline-flex;
          align-items: center;
          gap: 4px;
        }
        .typing-indicator span {
          width: 8px;
          height: 8px;
          background-color: #94a3b8;
          border-radius: 50%;
          animation: typing 1.4s infinite ease-in-out both;
        }
        .typing-indicator span:nth-child(1) {
          animation-delay: -0.32s;
        }
        .typing-indicator span:nth-child(2) {
          animation-delay: -0.16s;
        }
        @keyframes typing {
          0%,
          80%,
          100% {
            transform: scale(0);
          }
          40% {
            transform: scale(1);
          }
        }
      }
    </style>
  </head>
  <body class="bg-gray-50 min-h-screen flex flex-col">
    <!-- 顶部导航栏 -->
    <header class="bg-white shadow-sm border-b border-gray-200">
      <div
        class="container mx-auto px-4 py-4 flex justify-between items-center"
      >
        <div class="flex items-center gap-2">
          <i class="fa fa-car text-primary text-2xl"></i>
          <h1 class="text-xl font-bold text-gray-800">车载物流AI助手</h1>
        </div>
        <div class="flex items-center gap-4">
          <button
            id="clearChatBtn"
            class="text-gray-500 hover:text-gray-700 transition-colors duration-200"
          >
            <i class="fa fa-refresh mr-1"></i> 清空对话
          </button>
          <button
            id="themeToggle"
            class="text-gray-500 hover:text-gray-700 transition-colors duration-200"
          >
            <i class="fa fa-moon-o"></i>
          </button>
        </div>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="flex-1 container mx-auto px-4 py-6">
      <!-- 欢迎信息卡片 -->
      <div
        class="bg-gradient-to-r from-blue-50 to-green-50 rounded-2xl p-6 mb-6 shadow-sm border border-blue-100"
      >
        <div class="flex items-start gap-4">
          <div class="bg-primary/10 p-3 rounded-full">
            <i class="fa fa-info-circle text-primary text-xl"></i>
          </div>
          <div>
            <h2 class="text-lg font-semibold text-gray-800 mb-2">
              欢迎使用车载物流AI助手
            </h2>
            <p class="text-gray-600 mb-4">
              我是您的专业车载物流顾问，可以为您解答关于车载物流的基础概念、关键技术、业务流程、政策法规等问题。
            </p>
            <div class="flex flex-wrap gap-2">
              <span
                class="bg-blue-100 text-blue-800 text-xs px-3 py-1 rounded-full cursor-pointer hover:bg-blue-200 transition-colors"
                >基础概念</span
              >
              <span
                class="bg-green-100 text-green-800 text-xs px-3 py-1 rounded-full cursor-pointer hover:bg-green-200 transition-colors"
                >关键技术</span
              >
              <span
                class="bg-purple-100 text-purple-800 text-xs px-3 py-1 rounded-full cursor-pointer hover:bg-purple-200 transition-colors"
                >业务流程</span
              >
              <span
                class="bg-yellow-100 text-yellow-800 text-xs px-3 py-1 rounded-full cursor-pointer hover:bg-yellow-200 transition-colors"
                >政策法规</span
              >
            </div>
          </div>
        </div>
      </div>

      <!-- 对话历史区域 -->
      <div
        id="chatContainer"
        class="bg-white rounded-2xl shadow-sm border border-gray-200 p-4 h-[calc(100vh-320px)] overflow-y-auto scrollbar-hide"
      >
        <div id="chatHistory" class="space-y-6">
          <!-- 欢迎消息 -->
          <div class="flex gap-3 items-start">
            <div
              class="flex-shrink-0 w-10 h-10 bg-primary rounded-full flex items-center justify-center text-white"
            >
              <i class="fa fa-robot"></i>
            </div>
            <div class="flex-1">
              <div class="message-bubble-ai bg-gray-50 p-4 text-gray-800">
                <p>您好！我是车载物流AI助手，请问有什么可以帮助您的吗？</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>

    <!-- 输入区域 -->
    <footer class="bg-white border-t border-gray-200 py-4">
      <div class="container mx-auto px-4">
        <div class="flex gap-3 items-end">
          <div class="flex-1 relative">
            <textarea
              id="messageInput"
              class="w-full border border-gray-300 rounded-2xl px-4 py-3 focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary resize-none transition-all duration-200 h-24"
              placeholder="请输入您的问题..."
              rows="3"
            ></textarea>
            <div class="absolute bottom-3 right-3 text-gray-400 text-sm">
              <span id="charCount">0</span> 字符
            </div>
          </div>
          <button
            id="sendBtn"
            class="bg-primary hover:bg-primary/90 text-white rounded-full w-12 h-12 flex items-center justify-center transition-all duration-200 shadow-md hover:shadow-lg transform hover:-translate-y-0.5 disabled:opacity-50 disabled:cursor-not-allowed"
            disabled
          >
            <i class="fa fa-paper-plane"></i>
          </button>
        </div>
        <div class="text-center text-xs text-gray-400 mt-3">
          <p>车载物流AI助手 © 2023 | 基于专业知识库提供服务</p>
        </div>
      </div>
    </footer>

    <script>
      // 获取DOM元素
      const messageInput = document.getElementById("messageInput");
      const sendBtn = document.getElementById("sendBtn");
      const chatHistory = document.getElementById("chatHistory");
      const chatContainer = document.getElementById("chatContainer");
      const charCount = document.getElementById("charCount");
      const clearChatBtn = document.getElementById("clearChatBtn");
      const themeToggle = document.getElementById("themeToggle");
      const quickTopics = document.querySelectorAll(
        ".rounded-full.cursor-pointer"
      );

      // 生成或从本地存储获取memoryId
      let memoryId = localStorage.getItem("chatMemoryId");
      if (!memoryId) {
        // 生成新的memoryId（使用时间戳+随机数）
        memoryId =
          "chat_" + Date.now() + "_" + Math.floor(Math.random() * 10000);
        localStorage.setItem("chatMemoryId", memoryId);
      }

      // 字数统计
      messageInput.addEventListener("input", () => {
        const count = messageInput.value.length;
        charCount.textContent = count;

        // 启用/禁用发送按钮
        sendBtn.disabled = count === 0;
      });

      // 自动调整文本框高度
      messageInput.addEventListener("input", () => {
        messageInput.style.height = "auto";
        messageInput.style.height =
          Math.min(messageInput.scrollHeight, 120) + "px";
      });

      // 发送消息
      async function sendMessage() {
        const message = messageInput.value.trim();
        if (!message) return;

        // 清空输入框
        messageInput.value = "";
        charCount.textContent = "0";
        sendBtn.disabled = true;
        messageInput.style.height = "auto";

        // 添加用户消息到聊天历史
        addUserMessage(message);

        // 添加AI正在输入的提示
        const typingElement = addTypingIndicator();

        // 创建AbortController用于终止请求
        const controller = new AbortController();
        const signal = controller.signal;

        try {
          // 调用后端接口，传递signal和memoryId参数
          const response = await fetch(
            "/chat?message=" +
              encodeURIComponent(message) +
              "&memoryId=" +
              memoryId,
            { signal }
          );

          if (!response.ok) {
            throw new Error("请求失败");
          }

          // 移除正在输入的提示
          if (typingElement) {
            typingElement.remove();
          }

          // 添加AI响应消息容器（带终止按钮）
          const aiMessageContainer = addAiMessageContainerWithStop(controller);
          const aiMessageElement =
            aiMessageContainer.querySelector(".message-bubble-ai");

          // 处理流式响应
          const reader = response.body.getReader();
          const decoder = new TextDecoder();

          while (true) {
            const { done, value } = await reader.read();
            if (done) break;

            const chunk = decoder.decode(value, { stream: true });
            // 将内容添加到AI消息中
            aiMessageElement.innerHTML += chunk;

            // 滚动到底部
            chatContainer.scrollTop = chatContainer.scrollHeight;
          }
        } catch (error) {
          // 如果是主动中止的错误，显示相应消息
          if (error.name === "AbortError") {
            if (typingElement) {
              typingElement.remove();
            }
            addAiMessage("对话已终止。");
            return;
          }

          // 移除正在输入的提示
          if (typingElement) {
            typingElement.remove();
          }

          // 显示错误消息
          addAiMessage("抱歉，处理您的请求时出错了，请稍后再试。");
          console.error("Error:", error);
        }
      }

      // 添加用户消息到聊天历史
      function addUserMessage(message) {
        const messageElement = document.createElement("div");
        messageElement.className = "flex gap-3 items-start justify-end";
        messageElement.innerHTML = `
                <div class="flex-1 max-w-[80%]">
                    <div class="message-bubble-user bg-primary text-white p-4 rounded-lg shadow-sm"></div>
                </div>
                <div class="flex-shrink-0 w-10 h-10 bg-gray-200 rounded-full flex items-center justify-center text-gray-500">
                    <i class="fa fa-user"></i>
                </div>
            `;

        // 添加消息内容（处理换行和特殊字符）
        const messageBubble = messageElement.querySelector(
          ".message-bubble-user"
        );
        messageBubble.textContent = message;

        chatHistory.appendChild(messageElement);

        // 滚动到底部
        chatContainer.scrollTop = chatContainer.scrollHeight;
      }

      // 添加AI正在输入的提示
      function addTypingIndicator() {
        const typingElement = document.createElement("div");
        typingElement.className = "flex gap-3 items-start";
        typingElement.innerHTML = `
                <div class="flex-shrink-0 w-10 h-10 bg-primary rounded-full flex items-center justify-center text-white">
                    <i class="fa fa-robot"></i>
                </div>
                <div class="flex-1">
                    <div class="message-bubble-ai bg-gray-50 p-4 text-gray-800 rounded-lg">
                        <div class="typing-indicator">
                            <span></span>
                            <span></span>
                            <span></span>
                        </div>
                    </div>
                </div>
            `;

        chatHistory.appendChild(typingElement);

        // 滚动到底部
        chatContainer.scrollTop = chatContainer.scrollHeight;

        return typingElement;
      }

      // 添加带终止按钮的AI消息容器（用于流式响应）
      function addAiMessageContainerWithStop(controller) {
        const messageElement = document.createElement("div");
        messageElement.className = "flex gap-3 items-start";
        messageElement.innerHTML = `
                <div class="flex-shrink-0 w-10 h-10 bg-primary rounded-full flex items-center justify-center text-white">
                    <i class="fa fa-robot"></i>
                </div>
                <div class="flex-1">
                    <div class="message-bubble-ai bg-gray-50 p-4 text-gray-800 rounded-lg"></div>
                    <div class="flex justify-end mt-1 space-x-2">
                        <button class="text-gray-400 hover:text-gray-600 text-sm stop-btn">
                            <i class="fa fa-stop mr-1"></i>终止对话
                        </button>
                        <button class="text-gray-400 hover:text-gray-600 text-sm copy-btn">
                            <i class="fa fa-copy mr-1"></i>复制
                        </button>
                    </div>
                </div>
            `;

        chatHistory.appendChild(messageElement);

        // 滚动到底部
        chatContainer.scrollTop = chatContainer.scrollHeight;

        // 终止对话按钮事件
        const stopBtn = messageElement.querySelector(".stop-btn");
        stopBtn.addEventListener("click", () => {
          controller.abort();
          stopBtn.disabled = true;
          stopBtn.innerHTML = '<i class="fa fa-check mr-1"></i>已终止';
          stopBtn.classList.remove("text-gray-400", "hover:text-gray-600");
          stopBtn.classList.add("text-gray-500");
        });

        // 复制按钮事件
        const copyBtn = messageElement.querySelector(".copy-btn");
        copyBtn.addEventListener("click", () => {
          const textToCopy =
            messageElement.querySelector(".message-bubble-ai").textContent;
          navigator.clipboard.writeText(textToCopy).then(() => {
            const originalText = copyBtn.innerHTML;
            copyBtn.innerHTML = '<i class="fa fa-check mr-1"></i>已复制';
            setTimeout(() => {
              copyBtn.innerHTML = originalText;
            }, 2000);
          });
        });

        return messageElement;
      }

      // 添加AI消息（用于非流式响应或错误消息）
      function addAiMessage(message) {
        const messageElement = document.createElement("div");
        messageElement.className = "flex gap-3 items-start";
        messageElement.innerHTML = `
                <div class="flex-shrink-0 w-10 h-10 bg-primary rounded-full flex items-center justify-center text-white">
                    <i class="fa fa-robot"></i>
                </div>
                <div class="flex-1">
                    <div class="message-bubble-ai bg-gray-50 p-4 text-gray-800 rounded-lg"></div>
                    <div class="flex justify-end mt-1">
                        <button class="text-gray-400 hover:text-gray-600 text-sm copy-btn">
                            <i class="fa fa-copy mr-1"></i>复制
                        </button>
                    </div>
                </div>
            `;

        // 添加消息内容
        const messageBubble =
          messageElement.querySelector(".message-bubble-ai");
        messageBubble.textContent = message;

        chatHistory.appendChild(messageElement);

        // 滚动到底部
        chatContainer.scrollTop = chatContainer.scrollHeight;

        // 复制按钮事件
        const copyBtn = messageElement.querySelector(".copy-btn");
        copyBtn.addEventListener("click", () => {
          const textToCopy = messageBubble.textContent;
          navigator.clipboard.writeText(textToCopy).then(() => {
            const originalText = copyBtn.innerHTML;
            copyBtn.innerHTML = '<i class="fa fa-check mr-1"></i>已复制';
            setTimeout(() => {
              copyBtn.innerHTML = originalText;
            }, 2000);
          });
        });
      }

      // 清空对话
      function clearChat() {
        if (confirm("确定要清空所有对话记录吗？")) {
          // 询问是否同时重置对话记忆
          const resetMemory = confirm(
            "是否同时重置对话记忆？选择'确定'将开始新的对话上下文。"
          );

          if (resetMemory) {
            // 生成新的memoryId
            memoryId =
              "chat_" + Date.now() + "_" + Math.floor(Math.random() * 10000);
            localStorage.setItem("chatMemoryId", memoryId);
          }

          chatHistory.innerHTML = `
                    <div class="flex gap-3 items-start">
                        <div class="flex-shrink-0 w-10 h-10 bg-primary rounded-full flex items-center justify-center text-white">
                            <i class="fa fa-robot"></i>
                        </div>
                        <div class="flex-1">
                            <div class="message-bubble-ai bg-gray-50 p-4 text-gray-800">
                                <p>您好！我是车载物流AI助手，请问有什么可以帮助您的吗？</p>
                            </div>
                        </div>
                    </div>
                `;
          chatContainer.scrollTop = 0;
        }
      }

      // 切换深色/浅色模式（简单实现）
      function toggleTheme() {
        const isDark = document.body.classList.toggle("dark");
        if (isDark) {
          document.body.classList.add("bg-gray-900", "text-white");
          themeToggle.innerHTML = '<i class="fa fa-sun-o"></i>';
        } else {
          document.body.classList.remove("bg-gray-900", "text-white");
          themeToggle.innerHTML = '<i class="fa fa-moon-o"></i>';
        }
      }

      // 快速话题点击事件
      quickTopics.forEach((topic) => {
        topic.addEventListener("click", () => {
          messageInput.value = `请介绍一下车载物流中的${topic.textContent}相关内容`;
          messageInput.dispatchEvent(new Event("input"));
          messageInput.focus();
        });
      });

      // 发送按钮点击事件
      sendBtn.addEventListener("click", sendMessage);

      // 回车发送消息（按住shift+回车换行）
      messageInput.addEventListener("keydown", (e) => {
        if (e.key === "Enter" && !e.shiftKey) {
          e.preventDefault();
          if (sendBtn.disabled) return;
          sendMessage();
        }
      });

      // 清空对话按钮事件
      clearChatBtn.addEventListener("click", clearChat);

      // 主题切换按钮事件
      themeToggle.addEventListener("click", toggleTheme);
    </script>
  </body>
</html>
